﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.SQLite;
using System.Dynamic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using DataAchive.Helper;
using DataAchive.Model.DBModels;
using DataAchive.Model.ViewModels;
using DataAchive.Model;
using LiveCharts.Wpf;
using LiveCharts;
using Newtonsoft.Json;
using System.Xml;
using Microsoft.Win32;
using MySql.Data.MySqlClient;

namespace DataAchive
{
    /// <summary>
    /// StatisticsViWindow.xaml 的交互逻辑
    /// </summary>
    public partial class StatisticsViWindow : Window
    {
  
       // private ObservableCollection<string> _classIfyPriority;

        public StatisticsViViewModel _viViewModel { get; set; }
        private M_QueryBuilder queryBuilder = new M_QueryBuilder();
        public StatisticsViWindow()
        {
            InitializeComponent();
            _viViewModel = new StatisticsViViewModel();

            GetViClassIfyPrioritySetting();
            DataContext = _viViewModel; // 设置 DataContext 为 ViewModel
            //如果Y轴的值为0，图表上的数值不显示
            MonthStatisticsChart.AxisY[0].LabelFormatter = value => value <= 0 ? "" : value.ToString("N0");
            //初始化调用和按钮调用事件 UI生成会有冲突，暂时未初始化加载
            // 设置项生成器的跟踪级别为 High
            //System.Diagnostics.PresentationTraceSources.SetTraceLevel(StatisticsMonthData.ItemContainerGenerator, System.Diagnostics.PresentationTraceLevel.High);
            BtnSelectStatistics_Click(null, null);
            BtnSelectMonthStatistics_Click(null, null);

        }

        private void GetViClassIfyPrioritySetting()
        {
            XmlNode settingClassIfyPriority = Setting.GetXmlNode("setting/ViClassIfy/ClassIfyPriority");
            if (settingClassIfyPriority != null)
            {
                _viViewModel.ClassIfyPriorityArray.Clear();
                for (int i = 0; i < settingClassIfyPriority.ChildNodes.Count; i++)
                {
                    _viViewModel.ClassIfyPriorityArray.Add(settingClassIfyPriority.ChildNodes[i].InnerText);
                }
               // _classIfyPriority = _viViewModel.ClassIfyPriorityArray;
            }

        }


        /// <summary>
        /// 统计查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnSelectStatistics_Click(object sender, RoutedEventArgs e)
        {
            //获取源数据
        
            List<StatisticsClassifyModel> data = GetStatisticsSourceNew();
            //数据处理
          
            //数据绑定
            List<StatisticsClassifyModel> list = StatisticsDataProcessingNew(data);
            BindStatisticsDataNew(list);

         
        }

        /// <summary>
        /// 饼图数据绑定
        /// </summary>
        /// <param name="list"></param>
        private void BindStatisticsData(List<StatisticsClassifyModel> list)
        {
            #region 数据绑定
            var data = DataContext as StatisticsViViewModel;
    
            if (list != null && list.Any())
            {
                var OKModel = list.Find(x => x.ClassIfy == "OK");
                if (OKModel == null)
                {
                    OKModel = new StatisticsClassifyModel() { ClassIfy = "OK", Num = 0 };
                    list.Insert(0, OKModel);
                }
                //明细中不显示OK、NG
                list.Remove(OKModel);
                data.OKNum = (int)(OKModel == null ? 0 : OKModel.Num);
                var NGModel = list.Find(x => x.ClassIfy == "NG");
                data.NGNum = (int)(NGModel == null ? 0 : NGModel.Num);
                list.Remove(NGModel);
            }
            else
            {
                data.OKNum = 0;
                data.NGNum = 0;
            }
            #endregion
            list = list.OrderBy(w => Array.IndexOf(_viViewModel.ClassIfyPriorityArray.ToArray(), w.ClassIfy)).ToList();
            data.ClassIfyList = list;
            #region 饼图绑定
            StatisticsPieChart.Series.Clear();
            foreach (var item in data.ClassIfyList)
            {
                if (item.Num <= 0 || item.ClassIfy == "NG") continue;
                PieSeries pieSeries = new PieSeries();
                pieSeries.Title = item.ClassIfy;
                pieSeries.Values = new ChartValues<double> { item.Num };
                pieSeries.DataLabels = true;
                pieSeries.ToolTip = item.Num;
                pieSeries.Tag = item.Num;
                pieSeries.LabelPoint = chatPoint =>//显示内容格式化
                {
                    return string.Format("{0}({1})", item.ClassIfy, item.Num);
                };
                StatisticsPieChart.Series.Add(pieSeries);
            }

            // 设置鼠标悬停时的提示信息
            StatisticsPieChart.DataTooltip = new DefaultTooltip
            {
                SelectionMode = TooltipSelectionMode.SharedXValues
            };
            //
            #endregion

            DataContext = data;
        }

        private void BindStatisticsDataNew(List<StatisticsClassifyModel> list)
        {
            #region 数据绑定
            var data = DataContext as StatisticsViViewModel;
         

            #endregion
            //data.ClassIfyList = list;
            #region 饼图绑定
            StatisticsPieChart.Series.Clear();
            foreach (var item in data.ClassIfyList)
            {
                //if (item.Num <= 0 || item.ClassIfy == "NG") continue;
                PieSeries pieSeries = new PieSeries();
                pieSeries.Title = item.ClassIfy;
                pieSeries.Values = new ChartValues<double> { item.Num };
                pieSeries.DataLabels = true;
                pieSeries.ToolTip = item.Num;
                pieSeries.Tag = item.Num;
                pieSeries.LabelPoint = chatPoint =>//显示内容格式化
                {
                    return string.Format("{0}({1})", item.ClassIfy, item.Num);
                };
                StatisticsPieChart.Series.Add(pieSeries);
            }

            // 设置鼠标悬停时的提示信息
            StatisticsPieChart.DataTooltip = new DefaultTooltip
            {
                SelectionMode = TooltipSelectionMode.SharedXValues
            };
            //
            #endregion

        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="list">source Data</param>
        /// <returns></returns>
        private List<StatisticsClassifyModel> StatisticsDataProcessingNew(List<StatisticsClassifyModel> list, bool export = false)
        {
            var data = DataContext as StatisticsViViewModel;
            //汇总
            var okNumber = list.Where(x => x.ClassIfy == "OK").Sum(x => x.Num);
            var ngNumber = list.Where(x => x.ClassIfy == "NG").Sum(x => x.Num);//一行
            var totalNumber = ngNumber;
            var youLv = Math.Round(okNumber * 1m / (totalNumber == 0 ? 1 : totalNumber), 2) * 100;

            data.OKNum = Convert.ToInt32(okNumber);
            data.NGNum = Convert.ToInt32(ngNumber);//+ data.OKNum;

            //无数据
            if (list.Count() <= 1)
            {
                data.OKNum = 0;
                data.NGNum = 0;
            }

            var sourceData = JsonConvert.SerializeObject(list);
            var allData = JsonConvert.DeserializeObject<List<StatisticsClassifyModel>>(sourceData);
            //todo :  use?
            data.AllDataList = allData;

            //明细
            list.RemoveAll(x => x.ClassIfy == "OK");
            list.RemoveAll(x => x.ClassIfy == "NG");

            //总计
            var classfyGroup = list.GroupBy(x => x.ClassIfy);
            List<StatisticsClassifyModel> classifyModels = new List<StatisticsClassifyModel>();

            foreach (var itemClassfy in classfyGroup)
            {
                var classfyModel = new StatisticsClassifyModel();
                classfyModel.ClassIfy = itemClassfy.Key;
                classfyModel.DetailNum = Convert.ToInt32(itemClassfy.Sum(x => x.Num));
                // classfyModel.DetailNum = Convert.ToInt32(itemClassfy.Count());
                //classfyModel.NgIds = itemClassfy.Select(x => x.NgId).ToList();
                classifyModels.Add(classfyModel);
            }

            //sort
            List<StatisticsClassifyModel> sortClassifyModels = new List<StatisticsClassifyModel>();
            foreach (var itemClassfy in data.ClassIfyPriorityArray)
            {
                var item = classifyModels.Where(m => m.ClassIfy.Equals(itemClassfy)).FirstOrDefault();
                if (item != null)
                {
                    sortClassifyModels.Add(item);
                }
            }

            //source Data :classfy date(?) lotid
            //故障条码数量     
            //多个故障取优先级最高
            var lotList = list.GroupBy(x => x.LotId);

            HashSet<string> lotIds = new HashSet<string>();


            //foreach (var lotidGroup in lotList)
            //{

            //    foreach (var classfy in data.ClassIfyPriorityArray)
            //    {
            //        long classfyNumber = 0;
            //        var lotidList = list.Where(x => x.LotId == lotidGroup.Key).Where(x=>x.ClassIfy.Equals(classfy)).ToList();
            //        if (lotidList.Count() > 0)
            //        {
            //            classfyNumber++;
            //            lotIds.Add(lotidGroup.Key);
            //            //有一则跳出
            //            break;
            //        }
            //    }
            //}


            foreach (var classfy in data.ClassIfyPriorityArray)
            {
                long classfyNumber = 0;
                //ignore date
                foreach (var everyLotIds in list)
                {
                    if (!lotIds.Contains(everyLotIds.LotId) && everyLotIds.ClassIfy.Equals(classfy))
                    {
                        //classfyNumber= classfyNumber++
                        //classfyNumber = classfyNumber + everyLotId.Num;
                        classfyNumber++;
                        lotIds.Add(everyLotIds.LotId);
                        //下一条
                    }
                }
                var model = sortClassifyModels.Where(x => x.ClassIfy.Equals(classfy)).FirstOrDefault();
                if (model != null)
                {
                    model.Num = classfyNumber;
                }

            }

            foreach (var item in sortClassifyModels)
            {
                item.Rate = string.Format("{0:P}",
                        (double)item.Num / (data.NGNum == 0 ? 1 : data.NGNum));
            }

            data.ClassIfyList = sortClassifyModels;

            GetStatisticsListNew();

            if (export)
            {
                sortClassifyModels.Add(new StatisticsClassifyModel()
                {
                    ClassIfy = "NG",
                    Num = data.NGNum,
                });
                sortClassifyModels.Add(new StatisticsClassifyModel()
                {
                    ClassIfy = "OK",
                    Num = data.OKNum,
                });
            }
            return sortClassifyModels;

        }


        private void GetStatisticsListNew()
        {
            var data = DataContext as StatisticsViViewModel;
            if (data == null)
                return;

            var sourceData = JsonConvert.SerializeObject(data.AllDataList);
            var classifyModels = JsonConvert.DeserializeObject<List<StatisticsClassifyModel>>(sourceData);           

            //List<StatisticsClassifyModel> classifyModels = data.AllDataList;
            classifyModels.RemoveAll(x => x.ClassIfy == "OK");
            classifyModels.RemoveAll(x => x.ClassIfy == "NG");


            //var listData = classifyModels.Where(w => w.Num != 0 && w.ClassIfy != "OK" && w.ClassIfy != "NG");

            //数据
            //var dataNoGroup = classifyModels.OrderBy(o => o.LotId).Skip((data.StatisticsListData.PageIndex - 1) * data.StatisticsListData.PageSize)
            //    .Take(data.StatisticsListData.PageSize)
            //    .ToList();
            var gridRow = classifyModels.OrderBy(o => o.LotId).GroupBy(g => g.LotId).Skip((data.StatisticsListData.PageIndex - 1) * data.StatisticsListData.PageSize)
                .Take(data.StatisticsListData.PageSize)
                .ToList();


            //表头
            var columnList = new List<string>();

            //var allCol = classifyModels.GroupBy(g => g.ClassIfy).Select(s => s.Key).Where(w => w != "OK" && w != "NG").ToList();
            //allCol = allCol.OrderBy(w => Array.IndexOf(data.ClassIfyPriorityArray.ToArray(), w)).ToList();
            var allCol = GetHeadClassifyModels(1);
            allCol = allCol.OrderBy(w => Array.IndexOf(data.ClassIfyPriorityArray.ToArray(), w)).ToList();
            columnList.AddRange(allCol);
            //设置DataGrid列头
            StatisticsList.Columns.Clear();//清理掉原先的列

            var lotColumn = new DataGridTextColumn();  //第一列
            lotColumn.Header = "条码"; // 列标题为属性名
            lotColumn.Binding = new Binding(nameof(StatisticsClassifyModel.LotId)); // 绑定到对应属性
            lotColumn.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
            StatisticsList.Columns.Add(lotColumn);

            //第二列
            var NgColumn = new DataGridTextColumn();
            NgColumn.Header = "缺陷数量"; // 列标题为属性名
            NgColumn.Binding = new Binding("NG"); // 绑定到对应属性
            NgColumn.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
            StatisticsList.Columns.Add(NgColumn);
            //动态生成ClassIfy列
            if (columnList != null && columnList.Any())
            {
                foreach (var item in columnList)
                {
                    // 创建 DataGridTextColumn
                    var column = new DataGridTextColumn();
                    column.Header = item; // 列标题为属性名
                    column.Binding = new Binding(item); // 绑定到对应属性
                    column.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
                    StatisticsList.Columns.Add(column);
                }
            }

            // var lotIdGroup = listData.GroupBy(x=>x.LotId);

            //List<IDictionary<string, Object>> classfyDict = new List<IDictionary<string, object>>();         
            //foreach (var lotItems in lotIdGroup)
            //{
            //    IDictionary<string, Object> dic =new  Dictionary<string, Object>();
            //    dic.Add(nameof(StatisticsClassifyModel.LotId), lotItems.Key);
            //    dic.Add("NG", lotItems.Count());
            //    //各个详情
            //    //对比classfi名获取
            //    //按条码统计: 一个条码可能多个id，一个id具有某优先的故障，其它id的故障忽略统计
            //    foreach (var classfy in data.ClassIfyPriorityArray)
            //    {
            //        var classfyItem = lotItems.Where(x => x.ClassIfy.Equals(classfy)).FirstOrDefault();
            //        if(classfyItem!=null)
            //        {
            //           var faultNumer = lotItems.Where(x => x.ClassIfy.Equals(classfy)).Sum(x => x.Num);
            //            dic.Add(classfy,faultNumer);
            //            //执行下一个条码
            //            break;
            //        }
            //    }
            // classfyDict.Add(dic);
            //}
            if (data.StatisticsListData.Data == null)
                data.StatisticsListData.Data = new ObservableCollection<dynamic>();
            data.StatisticsListData.Data.Clear();

            foreach (var lotItems in gridRow)
            {
                dynamic expando = new ExpandoObject();
                var expandDict = expando as IDictionary<string, object>;
                expandDict[nameof(StatisticsClassifyModel.LotId)] = lotItems.Key;
                //expandDict["NG"] = lotItems.Count();
                expandDict["NG"] = lotItems.Sum(x => x.Num);

                //各个详情
                //对比classfi名获取
                //按条码统计: 一个条码可能多个id，一个id具有某优先的故障，其它id的故障忽略统计
                var ngitems = classifyModels.Where(x => x.LotId == lotItems.Key).ToList();
                foreach (var classfy in data.ClassIfyPriorityArray)
                {
                    //var classfyItem = ngitems.Where(x => x.ClassIfy.Equals(classfy)).FirstOrDefault();
                    //if (classfyItem != null)
                    //{

                    //     var faultNumer = lotItems.Where(x => x.ClassIfy.Equals(classfy)).Sum(x => x.Num);
                    //    // var faultNumer = lotItems.Where(x => x.ClassIfy.Equals(classfy)).Count();//1
                    //    //var faultNumer = ngitems.Where(x => x.ClassIfy.Equals(classfy)).Count();
                    //    expandDict[classfy] = faultNumer;                       
                    //    //执行下一个条码
                    //  //  break;
                    //}
                    var faultNumer = ngitems.Where(x => x.ClassIfy.Equals(classfy)).ToList()?.Sum(x => x.Num);
                    expandDict[classfy] = faultNumer;
                }
                data.StatisticsListData.Data.Add(expando);
            }



            //foreach (var item in classfyDict)
            //{
            //    data.StatisticsListData.Data.Add(item);
            //}           

            // data.StatisticsListData.Count = lotIdGroup.Count();
            data.StatisticsListData.Count = classifyModels.GroupBy(x => x.LotId).Count();
            int pageAdd = 0;
            if (data.StatisticsListData.Count % (data.StatisticsListData.PageSize == 0 ? 10 : data.StatisticsListData.PageSize) != 0)
                pageAdd += 1;
            data.StatisticsListData.PageCount = data.StatisticsListData.Count / (data.StatisticsListData.PageSize == 0 ? 10 : data.StatisticsListData.PageSize) + pageAdd;

        }


        /// <summary>
        /// 获取统计信息源数据 VI
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        private List<StatisticsClassifyModel> GetStatisticsSourceNew()
        {
            var data = DataContext as StatisticsViViewModel;
  
            string sql = $@"    select lotid,classify,ng.date ,count(*)as Num,GROUP_CONCAT(ngid,',')as ids from ng left join info on ng.id =info.ngId 
   where type=1
  and info.classify is not null
  and ng.date BETWEEN @StartTime AND @EndTime
   group by ng.lotid, info.classify
                                ";

            List<MySqlParameter> parameters = new List<MySqlParameter>();
            parameters.Add(new MySqlParameter("@StartTime", data.StartTime.ToString("yyyy-MM-dd HH:mm:ss")));
            parameters.Add(new MySqlParameter("@EndTime", data.EndTime.ToString("yyyy-MM-dd HH:mm:ss")));
            List<StatisticsClassifyModel> list = new List<StatisticsClassifyModel>();

            //while (data.StartTime.ToString("yyyy-MM") != data.EndTime.ToString("yyyy-MM"))
            //{
            //    queryBuilder = new QueryBuilder(data.StartTime);
            //    list.AddRange(queryBuilder.QuerySql<StatisticsClassifyModel>(sql, parameters.ToArray()));
            //    data.StartTime.Add    s(1);
            //}
            //queryBuilder = new QueryBuilder(data.EndTime);
            list.AddRange(queryBuilder.QuerySql<StatisticsClassifyModel>(sql, parameters.ToArray()));

            string sqlOk = $@"      select max(ng.id)as id, lotid,ng.date ,'OK' as classify,count(distinct(lotid))as Num,GROUP_CONCAT(ng.lotid,',')as ids from ng left join info on ng.id =info.ngId where info.classify is null 
    and ng.date  BETWEEN @StartTime AND @EndTime 
  and lotid not in(select  T.lotid from
    (select info.classify ,ng.lotid,count(*)as count from ng left join info on ng.id =info.ngId 
     group by info.classify ,ng.lotid )T group by  T.lotid having count(*)>1 ) ;
                                ";
            list.AddRange(queryBuilder.QuerySql<StatisticsClassifyModel>(sqlOk, parameters.ToArray()));

            string sqlNg = $@"    select max(T.id)as id, lotid,null as date,'NG' as classify,count(*)as Num,GROUP_CONCAT(t.id,',')as ids from (
   select max(info.id)as id, lotid,classify,max(ng.date)as date,count(*)as Num,max(ng.id)as ngid,GROUP_CONCAT(ngid,',')as ids from ng left join info on ng.id =info.ngId 
   where lotid not in(
     select lotid from ng left join info on ng.id =info.ngId where info.classify is null 
  and lotid not in(select  T.lotid from
    (select info.classify ,ng.lotid,count(*)as count from ng left join info on ng.id =info.ngId 
     group by info.classify ,ng.lotid )T group by  T.lotid having count(*)>1 )
  )
  and info.classify is not null 
  and ng.date BETWEEN @StartTime AND @EndTime
   group by ng.lotid
   )T";
            list.AddRange(queryBuilder.QuerySql<StatisticsClassifyModel>(sqlNg, parameters.ToArray()));
            return list;
        }

        private List<StatisticsClassifyModel> GetNgids(string fault)
        {
            List<StatisticsClassifyModel> lotids = new List<StatisticsClassifyModel>();
            var data = DataContext as StatisticsViViewModel;
            string sql = @"select ngid from ng left join info on ng.id = info.ngId
where info.classify = @fault and ng.date BETWEEN @StartTime AND @EndTime";
            List<MySqlParameter> parameters = new List<MySqlParameter>();
            parameters.Add(new MySqlParameter("@fault", fault));
            parameters.Add(new MySqlParameter("@StartTime", data.StartTime.ToString("yyyy-MM-dd HH:mm:ss")));
            parameters.Add(new MySqlParameter("@EndTime", data.EndTime.ToString("yyyy-MM-dd HH:mm:ss")));
            var res = queryBuilder.QuerySql<StatisticsClassifyModel>(sql, parameters.ToArray());
            lotids.AddRange(res);
            return lotids;
        }

        /// <summary>
        /// 获取缺陷头
        /// </summary>
        /// <returns></returns>
        private List<string> GetHeadClassifyModels(int type)
        {
            List<string> heads = new List<string>();
            var data = DataContext as StatisticsViViewModel;
            string sql = @"select distinct classify from ng inner join info on ng.id=info.ngid where type =@type and ng.date BETWEEN @StartTime AND @EndTime";
            List<MySqlParameter> parameters = new List<MySqlParameter>();
            parameters.Add(new MySqlParameter("@type", type));
            parameters.Add(new MySqlParameter("@StartTime", data.StartTime.ToString("yyyy-MM-dd HH:mm:ss")));
            parameters.Add(new MySqlParameter("@EndTime", data.EndTime.ToString("yyyy-MM-dd HH:mm:ss")));
            var res = queryBuilder.QuerySql<string>(sql, parameters.ToArray());
            heads.AddRange(res);
            return heads;

        }

        /// <summary>
        /// 查询月统计图
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnSelectMonthStatistics_Click(object sender, RoutedEventArgs e)
        {
            //获取源数据
            List<StatisticsClassifyModel> data = GetMonthStatisticsSource();
            //数据处理
            List<StatisticsClassifyModel> list = StatisticsMonthDataProcessing(data);

            //数据绑定
            BingMonthStatisticsData(list);
        }

        private List<StatisticsClassifyModel> StatisticsMonthDataProcessing(List<StatisticsClassifyModel> list)
        {
            List<StatisticsClassifyModel> resultList = new List<StatisticsClassifyModel>();
            List<StatisticsClassifyModel> lotList = new List<StatisticsClassifyModel>();
            foreach (var item in list.GroupBy(g => new { g.LotId, g.Date, g.Id }))
            {
                if (item.FirstOrDefault(f => f.ClassIfy == "OK") != null)
                {
                    lotList.Add(new StatisticsClassifyModel() { ClassIfy = "OK", Date = item.Key.Date, Num = item.Sum(s => s.Num) });
                }
                else if (item.FirstOrDefault(f => f.ClassIfy == "NG") != null)
                {
                    if (item.Sum(s => s.Num) > 0)
                        lotList.Add(new StatisticsClassifyModel() { ClassIfy = "NG", Num = item.Sum(s => s.Num), Date = item.Key.Date });
                }
                else
                {
                    foreach (var classIfy in _viViewModel.ClassIfyPriorityArray)
                    {
                        var classIfyInfo = item.FirstOrDefault(w => w.ClassIfy == classIfy);
                        if (classIfyInfo != null)
                        {
                            lotList.Add(new StatisticsClassifyModel() { ClassIfy = classIfy, Date = item.Key.Date, LotId = item.Key.LotId, Id = item.Key.Id });
                            break;
                        }
                    }
                }

            }

            foreach (var item in lotList.GroupBy(g => new { Date = g.Date.ToString("yyyy-MM-dd"), g.ClassIfy }))
            {


                string dateString = item.Key.Date;
                string format = "yyyy-MM-dd";
                DateTime dateTime;

                if (!DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime))
                    dateTime = new DateTime();

                if (item.Key.ClassIfy == "OK")
                {
                    resultList.Add(new StatisticsClassifyModel() { ClassIfy = "OK", Num = item.Sum(s => s.Num), Date = dateTime });
                }
                else if (item.Key.ClassIfy == "NG")
                {
                    resultList.Add(new StatisticsClassifyModel() { ClassIfy = "NG", Num = item.Sum(s => s.Num), Date = dateTime });
                }
                else
                {
                    resultList.Add(new StatisticsClassifyModel() { ClassIfy = item.Key.ClassIfy, Num = item.Count(), Date = dateTime });
                }
            }
            return resultList;

            //List<StatisticsClassifyModel> resultList = new List<StatisticsClassifyModel>();
            //List<StatisticsClassifyModel> lotList = new List<StatisticsClassifyModel>();
            //foreach (var item in list.GroupBy(g => new { g.LotId, g.Date }))
            //{
            //    if (item.FirstOrDefault(f => f.ClassIfy == "OK") != null)
            //    {
            //        lotList.Add(new StatisticsClassifyModel() { ClassIfy = "OK" });
            //    }
            //    else if (item.FirstOrDefault(f => f.ClassIfy == "NG") != null)
            //    {
            //        if (item.Sum(s => s.Num) > 0)
            //            lotList.Add(new StatisticsClassifyModel() { ClassIfy = "NG", Num = item.Sum(s => s.Num) });
            //    }
            //    else
            //    {
            //        foreach (var classIfy in _classIfyPriority)
            //        {
            //            var ngInfo = item.FirstOrDefault(w => w.ClassIfy == classIfy);
            //            if (ngInfo != null)
            //            {
            //                lotList.Add(new StatisticsClassifyModel() { ClassIfy = classIfy });
            //                break;
            //            }
            //        }
            //    }
            //}
            //var NGModel = lotList.Find(x => x.ClassIfy == "NG");
            //int NGNum = (int)(NGModel == null ? 0 : NGModel.Num);
            //foreach (var item in lotList.GroupBy(g => g.ClassIfy))
            //{
            //    if (item.Key == "NG")
            //        resultList.Add(new StatisticsClassifyModel() { ClassIfy = item.Key, Num = item.Sum(s => s.Num), Rate = string.Format("{0:P}", (double)item.Count() / (NGNum == 0 ? 1 : NGNum)) });
            //    else
            //        resultList.Add(new StatisticsClassifyModel() { ClassIfy = item.Key, Num = item.Count(), Rate = string.Format("{0:P}", (double)item.Count() / (NGNum == 0 ? 1 : NGNum)) });
            //}
            //return resultList;
        }

        /// <summary>
        /// 月统计图数据绑定
        /// </summary>
        /// <param name="time"></param>
        /// <param name="list"></param>
        private void BingMonthStatisticsData(List<StatisticsClassifyModel> list)
        {
            var data = DataContext as StatisticsViViewModel;
        
            //设置DataGrid列头
            StatisticsMonthData.Columns.Clear();//清理掉原先的列
                                                //第一列 Date
            var dataColumn = new DataGridTextColumn();
            dataColumn.Header = nameof(StatisticsClassifyModel.Date); // 列标题为属性名
            dataColumn.Binding = new Binding(nameof(StatisticsClassifyModel.Date)); // 绑定到对应属性
            dataColumn.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
            StatisticsMonthData.Columns.Add(dataColumn);
            //动态生成ClassIfy列
            if (list != null && list.Any())
            {
                var classIfyList = list.GroupBy(g => g.ClassIfy).ToList();
                classIfyList = ClassIfyListOrderBy(classIfyList);
                foreach (var item in classIfyList)
                {
                    // 创建 DataGridTextColumn
                    var column = new DataGridTextColumn();
                    column.Header = item.Key; // 列标题为属性名
                    column.Binding = new Binding(item.Key); // 绑定到对应属性
                    column.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
                    StatisticsMonthData.Columns.Add(column);
                }
            }

            //最后一列 总计
            var AmountColum = new DataGridTextColumn();
            AmountColum.Header = "总计"; // 列标题为属性名
            AmountColum.Binding = new Binding(nameof(StatisticsViewModel.Amount)); // 绑定到对应属性
            AmountColum.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
            StatisticsMonthData.Columns.Add(AmountColum);
            //从1号开始
            var time = data.MonthTime;
            var firstDayOfMonth = new DateTime(time.Year, time.Month, 1);
            //统计整月的数据
            data.MonthStatisticsListData.Clear();
            data.CartesianCharX.Clear();
            data.CartesianCharY.Clear();
            //只统计有信息的天数
            //foreach (var dateItem in list.GroupBy(g => new { g.Date }))
            for (int i = 0; i < firstDayOfMonth.AddMonths(1).AddDays(-1).Day; i++)
            {
                //日期
                var dayOfMonth = firstDayOfMonth.AddDays(i);
                string date = dayOfMonth.Date.ToString("yyyy-MM-dd");
                //当日数据
                var dateItem = list.Where(w => w.Date.ToString("yyyy-MM-dd") == date);
                //当日对象
                dynamic expando = new ExpandoObject();
                var expandoDict = expando as IDictionary<string, Object>;
                //第一列绑定值 日期
                expandoDict[nameof(StatisticsClassifyModel.Date)] = date;
                if (list != null && list.Any())
                {
                    var classIfyList = list.GroupBy(g => g.ClassIfy).ToList();
                    //调整OK/NG到前两列
                    classIfyList = ClassIfyListOrderBy(classIfyList);
                    //分类信息
                    foreach (var item in classIfyList)
                    {
                        expandoDict[item.Key] = dateItem.Where(w => w.ClassIfy == item.Key).Sum(s => s.Num);
                    }
                }
                //最后一列绑定值 总计
                //expandoDict[nameof(StatisticsViViewModel.Amount)] = dateItem.Where(w => w.ClassIfy != "NG").Sum(s => s.Num);
                expandoDict[nameof(StatisticsViViewModel.Amount)] = dateItem.Where(w => w.ClassIfy == "NG"|| w.ClassIfy == "OK").Sum(s => s.Num);
                data.MonthStatisticsListData.Add(expando);
                #region 统计图
                data.CartesianCharX.Add(date);
                // data.CartesianCharY.Add((int)dateItem.Where(w => w.ClassIfy != "NG").Sum(s => s.Num));
                data.CartesianCharY.Add((int)dateItem.Where(w => w.ClassIfy == "NG" || w.ClassIfy == "OK").Sum(s => s.Num));
                #endregion
            }
            data.CartesianCharData.Clear();
            data.CartesianCharData = new SeriesCollection()
            {
                //折线图
                 new LineSeries
                 {
                     Title ="LineChart",
                     Values = new ChartValues<int> (data.CartesianCharY)//Y轴数据集合
                 },
                 //柱状图
                new ColumnSeries
                {
                    Title = "Histogram",
                    DataLabels = true,//是否显示数据
                    Fill = System.Windows.Media.Brushes.DeepSkyBlue,//圆柱体颜色
                    Values = new ChartValues<int> (data.CartesianCharY)//Y轴数据集合
                }
            };
            DataContext = data;
        }

        /// <summary>
        /// 调整分类的顺序
        /// </summary>
        /// <param name="classIfyList"></param>
        private List<IGrouping<string, StatisticsClassifyModel>> ClassIfyListOrderBy(List<IGrouping<string, StatisticsClassifyModel>> classIfyList)
        {
            var OKColum = classIfyList.FirstOrDefault(w => w.Key == "OK");
            int ngIndex = 0;
            if (OKColum != null)
            {
                classIfyList.Remove(OKColum);
                classIfyList.Insert(0, OKColum);
                ngIndex = 1;
            }
            var NGColum = classIfyList.FirstOrDefault(w => w.Key == "NG");
            if (NGColum != null)
            {
                classIfyList.Remove(NGColum);
                classIfyList.Insert(ngIndex, NGColum);
            }

            return classIfyList.OrderBy(w => Array.IndexOf(_viViewModel.ClassIfyPriorityArray.ToArray(), w.Key)).ToList();

        }

        /// <summary>
        /// 获取月度统计信息源数据
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        private List<StatisticsClassifyModel> GetMonthStatisticsSource()
        {
            var data = DataContext as StatisticsViViewModel;
      
            var time = data.MonthTime;
            //string sql = $@"SELECT COALESCE(i.classify, 'OK') AS ClassIfy,COUNT(*) as Num,n.date as Date
            //                FROM ng n
            //                LEFT JOIN info i ON i.ngId = n.id
            //                WHERE strftime('%Y-%m', n.date) = @DateTime
            //                GROUP BY COALESCE(i.classify, 'OK'),date( n.date)
            //                UNION ALL
            //                SELECT 'NG' as ClassIfy,
            //                       COUNT(*) as Num,
            //                       ng.date as Date
            //                FROM ng 
            //                WHERE EXISTS (
            //                        SELECT 1
            //                        FROM info
            //                        WHERE info.ngId = ng.id
            //                )
            //                AND strftime('%Y-%m', ng.date) = @DateTime
            //                GROUP BY Date;";

            //string sql = $@"SELECT lotid AS Lotid,date AS Date,classify AS Classify,Num FROM 
            //                    (SELECT ngId,classify,COUNT(1) AS NUM FROM info i GROUP BY ngId,classify) A 
            //                LEFT JOIN ng n ON A.ngId = n.id 
            //                WHERE strftime('%Y-%m', Date) = @DateTime 
            //                UNION ALL 
            //                SELECT n.lotid AS Lotid,n.date AS Date ,'OK' AS Classify ,COUNT(*) AS Num
            //                FROM ng n 
            //                LEFT JOIN info i ON n.id = i.ngId 
            //                WHERE i.id IS NULL AND strftime('%Y-%m', Date) = @DateTime 
            //                GROUP BY strftime('%Y-%m-%d', n.date)
            //                UNION ALL
            //                SELECT 
            //                    '' AS Lotid,
            //                    date AS Date,
            //                    'NG' AS Classify,
            //                    COUNT(*) AS Num
            //                FROM ng
            //                WHERE EXISTS (
            //                    SELECT 1
            //                    FROM info
            //                    WHERE info.ngId = ng.id
            //                ) AND strftime('%Y-%m', Date) = @DateTime
            //                GROUP BY strftime('%Y-%m-%d', date);";

            string sql = $@"SELECT n.id AS Id,lotid AS Lotid,date AS Date,classify AS Classify,Num FROM 
                                (SELECT ngId,classify,COUNT(1) AS NUM FROM info i GROUP BY ngId,classify) A 
                            LEFT JOIN ng n ON A.ngId = n.id 
                            WHERE  DATE_FORMAT(Date, '%Y-%m') = @DateTime
                            UNION ALL 
                            SELECT n.id AS Id, n.lotid AS Lotid,n.date AS Date ,'OK' AS Classify ,COUNT(*) AS Num
                            FROM ng n 
                            LEFT JOIN info i ON n.id = i.ngId 
                            WHERE i.id IS NULL AND DATE_FORMAT(Date, '%Y-%m') = @DateTime
                            GROUP BY  DATE_FORMAT(Date, '%Y-%m') = @DateTime
                            UNION ALL
                            SELECT 
                                id AS Id,
                                '' AS Lotid,
                                date AS Date,
                                'NG' AS Classify,
                                COUNT(*) AS Num
                            FROM ng
                            WHERE EXISTS (
                                SELECT 1
                                FROM info
                                WHERE info.ngId = ng.id
                            ) AND  DATE_FORMAT(Date, '%Y-%m') = @DateTime
                            GROUP BY  DATE_FORMAT(Date, '%Y-%m') = @DateTime;";

            List<MySqlParameter> parameters = new List<MySqlParameter>();
            parameters.Add(new MySqlParameter("@DateTime", time.ToString("yyyy-MM")));
            queryBuilder = new M_QueryBuilder();
            var list = queryBuilder.QuerySql<StatisticsClassifyModel>(sql, parameters.ToArray());
            return list;
        }

        /// <summary>
        /// 月度统计导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnExportMonthStatistics_Click(object sender, RoutedEventArgs e)
        {
            var data = DataContext as StatisticsViViewModel;
            
            if (data.MonthStatisticsListData == null || !data.MonthStatisticsListData.Any())
            {
                //获取源数据
                List<StatisticsClassifyModel> dataList = GetMonthStatisticsSource();
                //数据处理
                List<StatisticsClassifyModel> list = StatisticsMonthDataProcessing(dataList);
                //数据绑定
                BingMonthStatisticsData(list);
            }
            // 创建一个 SaveFileDialog 实例
            SaveFileDialog saveFileDialog = new SaveFileDialog()
            {
                FileName = $"月度统计报表-{data.MonthTime.ToString("yyyy年MM月")}.xlsx",//默认文件名
                Title = "保存文件",// 设置对话框标题
                Filter = " 全部文件 |*.xlsx;*.xls;*.csv| Excel表格文档 (*.xlsx;*.xls;)|*.xlsx;*.xls| CSV文档 (*.csv)|*.csv"// 设置默认的文件类型过滤器
            };
            // 如果用户在对话框中选择了一个文件并点击了“保存”
            if (saveFileDialog.ShowDialog() == true)
            {
                try
                {
                    //获取用户选择的文件路径
                    string filePath = saveFileDialog.FileName;
                    //重新指定列名 通过键值对修改动态实体的属性
                    Dictionary<string, string> DicColumsName = new Dictionary<string, string>();
                    DicColumsName.Add(nameof(StatisticsViewModel.Amount), "总计");
                    ExcelHelper.Export(filePath, data.MonthStatisticsListData.ToList(), _viViewModel.ClassIfyPriorityArray, data.MonthTime.ToString("yyyy-MM"), DicColumsName);

                    // 显示保存成功信息
                    MessageBox.Show("保存成功！", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                catch (Exception ex)
                {
                    // 显示错误信息
                    MessageBox.Show($"保存文件时出错: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        private void PrioritySetting_Click(object sender, RoutedEventArgs e)
        {
            if (!PriorityPopup.IsOpen)
                PriorityPopup.IsOpen = true;
            else
                PriorityPopup.IsOpen = false;
        }

        private void ListBoxItem_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            ListBoxItem listBoxItem = sender as ListBoxItem;
            DragDrop.DoDragDrop(listBoxItem, listBoxItem.DataContext, DragDropEffects.Move);
        }
        private void ListBoxItem_Drop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(typeof(string)))
            {
                string droppedData = (string)e.Data.GetData(typeof(string));
                var target = (ListBoxItem)sender;
                string targetData = (string)target.DataContext;

                int sourceIndex = _viViewModel.ClassIfyPriorityArray.IndexOf(droppedData);
                int targetIndex = _viViewModel.ClassIfyPriorityArray.IndexOf(targetData);

                Move(_viViewModel.ClassIfyPriorityArray, sourceIndex, targetIndex);
            }
        }

        private void Move<T>(ObservableCollection<T> collection, int oldIndex, int newIndex)
        {
            if (oldIndex < 0 || oldIndex >= collection.Count || newIndex < 0 || newIndex >= collection.Count)
                return;

            T item = collection[oldIndex];
            collection.RemoveAt(oldIndex);
            collection.Insert(newIndex, item);
        }


        private void UpdatePrioritySetting_Click(object sender, RoutedEventArgs e)
        {
            XmlNode xmlNode = Setting.GetXmlNode("setting/ClassIfy/ClassIfyPriority");
            xmlNode.RemoveAll();
            // 遍历参数数组，为每个元素创建一个新的 <Item> 元素，并添加到父节点下
            foreach (var newItem in _viViewModel.ClassIfyPriorityArray)
            {
                XmlElement newItemElement = xmlNode.OwnerDocument.CreateElement("String");
                newItemElement.InnerText = newItem;
                xmlNode.AppendChild(newItemElement);
            }
            Setting.Save();
            PriorityPopup.IsOpen = false;
        }

        private void CencelPrioritySetting_Click(object sender, RoutedEventArgs e)
        {
            PriorityPopup.IsOpen = false;
        }

        private void StatisticsItem_MouseLeave(object sender, MouseEventArgs e)
        {
            Grid grid = sender as Grid;
            grid.Background = LightenColor(grid.Background as SolidColorBrush, 50);
        }

        private void StatisticsItem_MouseEnter(object sender, MouseEventArgs e)
        {
            Grid grid = sender as Grid;
            grid.Background = LightenColor(grid.Background as SolidColorBrush, -50);
        }
        public static SolidColorBrush LightenColor(SolidColorBrush solidColorBrush, double amount)
        {
            System.Windows.Media.Color color = solidColorBrush.Color;
            // 计算新的 R、G、B 值
            byte r = (byte)(color.R + amount);
            byte g = (byte)(color.G);
            byte b = (byte)(color.B);

            // 创建新的 Color 对象
            System.Windows.Media.Color newColor = System.Windows.Media.Color.FromArgb(color.A, r, g, b);
            solidColorBrush.Color = newColor;
            return solidColorBrush;
        }

        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var data = DataContext as StatisticsViViewModel;
            if (data == null)
            {
                return;
            }
            ComboBox comboBox = sender as ComboBox;
            if (comboBox.SelectedItem != null)
            {
                ComboBoxItem selectedItem = (ComboBoxItem)comboBox.SelectedItem;
                int selectedTag = Convert.ToInt32(selectedItem.Tag);
                data.StatisticsListData.PageIndex = 1;
                data.StatisticsListData.PageSize = selectedTag;
                // GetStatisticsList();
                GetStatisticsListNew();


                int pageAdd = 0;
                if (data.StatisticsListData.Count % (data.StatisticsListData.PageSize == 0 ? 10 : data.StatisticsListData.PageSize) != 0)
                    pageAdd += 1;
                data.StatisticsListData.PageCount = data.StatisticsListData.Count / (data.StatisticsListData.PageSize == 0 ? 10 : data.StatisticsListData.PageSize) + pageAdd;
            }
        }

        private void Pagination_CurrentIndexChanged(object sender, Panuon.UI.Silver.Core.CurrentIndexChangedEventArgs e)
        {
            // GetStatisticsList
            GetStatisticsListNew();
        }

        private void BtnExportStatistics_Click(object sender, RoutedEventArgs e)
        {
            string message = "";
            var data = DataContext as StatisticsViViewModel;
  
            List<StatisticsClassifyModel> listSum = null;

            //获取源数据
            //List<StatisticsClassifyModel> dataSource = GetStatisticsSource();
            //获取源数据
            List<StatisticsClassifyModel> dataSource = GetStatisticsSourceNew();
            //数据处理
            //listSum = StatisticsDataProcessing(dataSource);
            listSum = StatisticsDataProcessingNew(dataSource, true);



            // 创建一个 SaveFileDialog 实例
            SaveFileDialog saveFileDialog = new SaveFileDialog()
            {
                FileName = $"统计报表-{data.MonthTime.ToString("yyyyMMddHHmmss")}.xlsx",//默认文件名
                Title = "保存文件",// 设置对话框标题
                Filter = " 全部文件 |*.xlsx;*.xls;*.csv| Excel表格文档 (*.xlsx;*.xls;)|*.xlsx;*.xls| CSV文档 (*.csv)|*.csv"// 设置默认的文件类型过滤器
            };

            try
            {
                string path = string.Empty;
                // 如果用户在对话框中选择了一个文件并点击了“保存”
                if (saveFileDialog.ShowDialog() == true)
                {
                    //获取用户选择的文件路径
                    string filePath = saveFileDialog.FileName;
                    path = System.IO.Directory.GetParent(filePath).FullName;
                    //重新指定列名 通过键值对修改动态实体的属性
                    Dictionary<string, string> DicColumsName = new Dictionary<string, string>();
                    DicColumsName.Add(nameof(StatisticsClassifyModel.LotId), "条码");
                    //var list = ExportStatisticsList();
                    var list = ExportStatisticsListNew();
                    message = ExcelHelper.Export(filePath, list, listSum, _viViewModel.ClassIfyPriorityArray, "缺陷信息", DicColumsName);

                    // GetStatisticsList();                    
                }
                else
                {
                    //cancel
                    return;
                }
                if (string.IsNullOrEmpty(message))
                {
                    // 显示保存成功信息
                    MessageBox.Show("保存成功！", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                    FileHelper folderHelper = new FileHelper();
                    folderHelper.OpenFolder(path);
                }
                else
                {
                    // 显示错误信息
                    MessageBox.Show($"保存文件时出错: {message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (Exception ex)
            {
                //记录日志
            }
        }


        private List<dynamic> ExportStatisticsListNew()
        {
            var data = DataContext as StatisticsViViewModel;
          

            var sourceData = JsonConvert.SerializeObject(data.AllDataList);
            var classifyModels = JsonConvert.DeserializeObject<List<StatisticsClassifyModel>>(sourceData);

            //List<StatisticsClassifyModel> classifyModels = data.AllDataList;

            var okLotIds = classifyModels.Where(x => x.ClassIfy == "OK").ToList();
            classifyModels.RemoveAll(x => x.ClassIfy == "OK");
            classifyModels.RemoveAll(x => x.ClassIfy == "NG");


            //var listData = classifyModels.Where(w => w.Num != 0 && w.ClassIfy != "OK" && w.ClassIfy != "NG");

            //数据
            var gridRow = classifyModels.OrderBy(o => o.LotId).GroupBy(g => g.LotId)
                .ToList();
            //表头
            var columnList = new List<string>();

            //var allCol = classifyModels.GroupBy(g => g.ClassIfy).Select(s => s.Key).Where(w => w != "OK" && w != "NG").ToList();
            //allCol = allCol.OrderBy(w => Array.IndexOf(data.ClassIfyPriorityArray.ToArray(), w)).ToList();
            var allCol = GetHeadClassifyModels(1);
            allCol = allCol.OrderBy(w => Array.IndexOf(data.ClassIfyPriorityArray.ToArray(), w)).ToList();
            columnList.AddRange(allCol);

            List<dynamic> lotItemList = new List<dynamic>();
            foreach (var lotItems in gridRow)
            {
                dynamic expando = new ExpandoObject();
                var expandDict = expando as IDictionary<string, object>;
                expandDict[nameof(StatisticsClassifyModel.LotId)] = lotItems.Key;
                expandDict["NG"] = lotItems.Count();

                //HEAD
                foreach (var item in columnList)
                {

                    expandDict[item] = 0;
                }
                expandDict["OK"] = 0;

                //各个详情
                //对比classfi名获取
                //按条码统计: 一个条码可能多个id，一个id具有某优先的故障，其它id的故障忽略统计
                foreach (var classfy in data.ClassIfyPriorityArray)
                {
                    var classfyItem = lotItems.Where(x => x.ClassIfy.Equals(classfy)).FirstOrDefault();
                    if (classfyItem != null)
                    {
                        var faultNumer = lotItems.Where(x => x.ClassIfy.Equals(classfy)).Sum(x => x.Num);
                        // var faultNumer = lotItems.Where(x => x.ClassIfy.Equals(classfy)).Count();//1
                        // var faultNumer = ngitems.Where(x => x.ClassIfy.Equals(classfy)).Count();
                        expandDict[classfy] = faultNumer;
                        //执行下一个条码
                        // break;
                    }
                }
                lotItemList.Add(expando);
            }
            //var okGrp =okLotIds.GroupBy(x => x.LotId);
            //foreach (var item in okGrp)
            //{
            //    dynamic expando = new ExpandoObject();
            //    var expandic =expando as IDictionary<string, object>;
            //    expandic[nameof(StatisticsClassifyModel.LotId)] = item.Key;
            //    expandic["OK"] = item.Count();//多个id
            //    lotItemList.Add(expandic);
            //    foreach (var col in columnList)
            //    {

            //        expandic[col] = 0;
            //    }
            //}
            var okGrp = okLotIds.FirstOrDefault()?.Ids.Split(',').Distinct();
            foreach (var item in okGrp)
            {
                dynamic expando = new ExpandoObject();
                var expandic = expando as IDictionary<string, object>;
                expandic[nameof(StatisticsClassifyModel.LotId)] = item;
                expandic["OK"] = 1;//多个id
                lotItemList.Add(expandic);
                foreach (var col in columnList)
                {

                    expandic[col] = 0;
                }
            }


            return lotItemList;


        }

        private static InfoWindow infoWindow;
        private void StatisticsItem_MouseDown(object sender, MouseButtonEventArgs e)
        {
            StatisticsClassifyModel data = (sender as Grid).DataContext as StatisticsClassifyModel;
            //string a = data.LotId;
            AChiveInfo model = new AChiveInfo() { Classify = data.ClassIfy };
            if (data.NgIds is null)
            {
                data.NgIds = GetNgids(data.ClassIfy).Select(x => x.NgId).ToList();
            }
            List<FilterModel> filterModel = new List<FilterModel>()
            {
                new FilterModel(){Name="ngId",Type=FilterType.In,In = data.NgIds.Select(s=> (object)s).ToArray()}
            };
            if (infoWindow == null || !infoWindow.IsVisible)
            {
                object[] param = { new object[] { new NgData(), model, filterModel } };
                ActivatorHelper.GetInstance<InfoWindow>(ref infoWindow, param);
                infoWindow.Closed += (s, eventArgs) => infoWindow = null; // 当 SecondWindow 关闭时释放资源
                infoWindow.Show();
            }
            else
            {
                infoWindow.Activate(); // 如果 SecondWindow 已经存在，则激活它
            }
        }
    }
}